<template>
  <div style="width: 100%">
    <div style="margin: 10px 0 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button>其它</el-button>
    </div>
    <div style="margin: 10px 0 10px 0">
      <el-input v-model="search" placeholder=" 请 输 入 关 键 字 " style="width:30%"></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="list">查询</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 1300px;">
      <!--<el-table-column prop="imgPath" label="图片"></el-table-column>-->
      <!--<el-table-column sortable prop="date" label="日期"></el-table-column>-->
      <el-table-column align="center" label="图片" width="180">
        <template #default="scope">
          <div style="display: flex; align-items: center;">
            <!--<el-image :preview-src-list="srcList" />-->
            <el-image preview-teleported="true" :src="'/src/' + scope.row.imgPath"/>
            <!--<el-image preview-teleported="true" :src="'/src/' + scope.row.imgPath" :preview-src-list="srcList" />-->
            <!--<el-image preview-teleported="imgPath" />-->
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable prop="id" label="ID"></el-table-column>
      <el-table-column align="center" prop="name" label="作者"></el-table-column>
      <el-table-column align="center" sortable prop="datetime" label="日期"></el-table-column>
      <el-table-column align="center" prop="text" label="内容"></el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button style="width: 40px" @click="handleEdit(scope.row)" type="primary">编辑</el-button>
          <el-button style="width: 40px" @click="checkComment(scope.row.id)" type="primary">查看</el-button>
          <!--<el-button @click="del(scope.row.id)" type="text">删除</el-button>-->
          <el-popconfirm title="你确定要删除该数据吗？" @confirm="del(scope.row.id)">
            <template #reference>
              <el-button style="width: 40px" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding-left: 25%;padding-top: 10px;tab-size: 16px">
      <el-pagination
          small
          background
          layout="prev, pager, next, sizes, total, jumper"
          class="mt-4"
          @size-change="pageSizeChange"
          @current-change="currentChange"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[4,8]"
          :page-size="pageSize"
      />
    </div>
  </div>
  <div>
    <el-dialog title="添加公告："
               v-model="dialogVisible" :before-close="handleClose" width="30%">
      <el-form enctype="multipart/form-data" :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="图片" v-model="form.imgPath" prop="imgPath">
          <el-upload
              name="img"
              list-type="picture-card"
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <el-icon v-if="!dialogImageUrl"><Plus/></el-icon>
            <img v-if="dialogImageUrl!=''" :src="'/src/' + dialogImageUrl" class="avatar" style="width: 148px; height: 148px">
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" prop="name">
          <el-input v-model="form.name" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.text" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false; deleteLastImg('')">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <el-dialog v-model="dialogTableVisible" title="订单详情">
    <el-table :data="gridData">
      <el-table-column align="center" property="memberId" label="用户ID" style="width: 80%"/>
      <el-table-column align="center" property="name" label="用户" style="width: 80%"/>
      <el-table-column align="center" sortable property="datetime" label="日期" style="width: 80%"/>
      <el-table-column align="center" property="message" label="评论" style="width: 80%"/>
    </el-table>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import request from "@/utils/request.js";

export default {
  name: "announcement",
  data(){
    return {
      pageSize: 4,
      currentPage: 1,
      total: 5,
      dialogTableVisible: false,
      dialogVisible: false,
      disabled: false,
      dialogImageUrl: '',
      form: {},
      search: '',
      gridData: [],
      tableData: [
        {
          imgPath: '',
          id: 1,
          name: 'belly',
          datetime: '2023-10-15',
          text: 'HelloWorld'
        },
      ],
      ann: [],
    }
  },
  created() {
    this.announcementList();
  },
  methods: {
    currentChange(pageNum) {
      this.currentPage = pageNum;
      this.announcementList();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.announcementList();
    },
    add() {
      sessionStorage.removeItem("dialogImageUrl");
      this.dialogVisible = true;
      this.dialogImageUrl = '';
      this.form = {};
    },
    handleAvatarSuccess(res, file){
      console.log("res=", res);
      if (res.code === '200'){
        this.deleteLastImg('图片更换成功');
        sessionStorage.setItem("dialogImageUrl", res.data);
        this.dialogImageUrl = res.data;
        ElMessage({
          message: '图片加载成功',
          type: 'success',
        })
      }
      if (res.code === '555'){
        ElMessage({
          message: '上传的图片上传图片失败',
          type: 'error',
        })
      }
    },
    beforeAvatarUpload(file){
      const isLimitFile = file.size / 1024 / 1024 < 2;
      if (!isLimitFile){
        ElMessage({
          message: '上传的图片不能超过2MB',
          type: 'error',
        })
      }
    },
    deleteLastImg(msg){
      //删除替换前的照片
      if (sessionStorage.getItem("dialogImageUrl")){
        request.get("/api/deleteLastImg",{
          params: {
            lastImageUrl: sessionStorage.getItem("dialogImageUrl")
          }
        }).then(
            res => {
              if (res.code === "200"){
                if (msg){
                  ElMessage({
                    message: msg,
                    type: 'success',
                  })
                }
              }else {
                ElMessage({
                  message: '图片更改失败',
                  type: 'error',
                })
              }
            }
        )
      }
    },
    handleClose(){
      ElMessageBox.confirm('你确定要退出')
          .then(() => {
            this.deleteLastImg('');
            this.dialogVisible = false;
          })
          .catch(() => {
            // catch error
          })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      sessionStorage.setItem("dialogImageUrl", row.imgPath);
      this.dialogImageUrl = row.imgPath;
      this.dialogVisible = true;
      // this.$refs['form'].resetFields();//将上传验证消息清空
    },
    checkComment(id){
      this.dialogTableVisible = true;
      request.get("/api/commentList", {
        params: {
          announcementId: id
        }
      }).then(
          res => {
            if (res.code === '200'){
              this.gridData = res.data;
            }
            if (res.code === '555'){
              ElMessage({
                message: '拉取数据失败',
                type: 'error',
              })
            }
          }
      )
    },
    save(){
      if (this.form.id){
        this.form.imgPath = this.dialogImageUrl;
        request.put("/api/updateAnnouncement", this.form).then(
            res => {
              if (res.code === "200"){
                ElMessage({
                  message: '修改成功',
                  type: 'success',
                })
                sessionStorage.removeItem("dialogImageUrl");
              }else {
                ElMessage({
                  message: '修改失败',
                  type: 'error',
                })
              }
              this.announcementList();
              this.dialogVisible = false;
            }
        )
      }else {
        this.form.imgPath = this.dialogImageUrl;
        request.post("/api/addAnnouncement", this.form).then(
            res => {
              console.log("res=", res);
              if (res.code === '200'){
                ElMessage({
                  message: res.msg,
                  type: 'success',
                })
                this.dialogVisible = false;
                this.dialogImageUrl = '';
                sessionStorage.removeItem("dialogImageUrl");
                this.announcementList();
              }
              if (res.code === '555'){
                ElMessage({
                  message: '提交失败',
                  type: 'error',
                })
              }
            }
        )
      }
    },
    del(id){
      request.delete("/api/delAnnouncement/" + id).then(
          res => {
            if (res.code === '200'){
              ElMessage({
                message: res.msg,
                type: 'success',
              })
            }
            if (res.code === '555'){
              ElMessage({
                message: '删除失败',
                type: 'error',
              })
            }
            this.announcementList();
          }
      )
    },
    announcementList(){
      request.get("/api/adminAnnList", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          searchName: this.search
        }
      }).then(
          res => {
            console.log("res=", res)
            if (res.code === '200'){
              this.tableData = res.data.records;
              this.total = res.data.total;
            }
            if (res.code === '555'){
              ElMessage({
                message: '拉取数据失败',
                type: 'error',
              })
            }
          }
      )
    },

  }
}
</script>

<style scoped>

</style>